#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_settingsDialog = new SettingsDialog(this);
    m_textSearchDialog = new TextSearchDialog(this);
    createActions();
    initActions();
    initObject();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::createActions()
{
    popMenu_L = new QMenu();
    QAction *actionDelDir = new QAction("删除");
    popMenu_L->addAction(actionDelDir);
    connect(actionDelDir, &QAction::triggered, this, &MainWindow::deleteDir);

    QAction *actionShowDir = new QAction("在Explorer中显示");
    popMenu_L->addAction(actionShowDir);
    connect(actionShowDir, &QAction::triggered, this, &MainWindow::showDir);

    popMenu_R = new QMenu();
    QAction *actionDelFile = new QAction("删除");
    popMenu_R->addAction(actionDelFile);
    connect(actionDelFile, &QAction::triggered, this, &MainWindow::deleteFile);

    QAction *actionShowFile = new QAction("在Explorer中显示");
    popMenu_R->addAction(actionShowFile);
    connect(actionShowFile, &QAction::triggered, this, &MainWindow::showFile);

    // 添加搜索按钮
    QAction* searchAction = new QAction(QIcon(":/icons/search.png"), tr("Search"), this);
    searchAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_H));
    ui->toolBar->addAction(searchAction);
    connect(searchAction, &QAction::triggered, m_textSearchDialog, &QDialog::show);
}

void MainWindow::initActions()
{
    connect(ui->actionNew, &QAction::triggered, this, &MainWindow::newDocument);
    connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::open);
    connect(ui->actionSave, &QAction::triggered, this, &MainWindow::save);
    connect(ui->actionSave_as, &QAction::triggered, this, &MainWindow::saveAsAct);
    connect(ui->actionCopy, &QAction::triggered, this, &MainWindow::copy);
    connect(ui->actionCut, &QAction::triggered, this, &MainWindow::cut);
    connect(ui->actionPaste, &QAction::triggered, this, &MainWindow::paste);
    connect(ui->actionUndo, &QAction::triggered, this, &MainWindow::undo);
    connect(ui->actionRedo, &QAction::triggered, this, &MainWindow::redo);
    connect(ui->actionFont, &QAction::triggered, this, &MainWindow::selectFont);
    connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::about);
    connect(ui->actionExit, &QAction::triggered, this, &MainWindow::exit);
    //m_settingsDialog
    connect(ui->actionSetting, &QAction::triggered, m_settingsDialog, &QDialog::show);
    //
    //QsciScintilla 必须使用 SIGNAL SLOT 方式连接信号槽
    //connect(ui->frame, &QsciScintilla::textChanged, this, &MainWindow::on_plainTextEdit_textChanged);
    connect(ui->frame, SIGNAL(textChanged()), this, SLOT(on_plainTextEdit_textChanged()));

    connect(ui->frame, SIGNAL(SCN_FOCUSIN()), this, SLOT(scn_focusin()));//获得焦点
    connect(ui->frame, SIGNAL(SCN_FOCUSOUT()), this, SLOT(scn_focusout()));//失去焦点
}

void MainWindow::initObject()
{
    list1 = ui->list1;
    list2 = ui->list2;
    list1->setFrameShape(QListWidget::NoFrame);
    list2->setFrameShape(QListWidget::NoFrame);
    QToolBar *toolBar = ui->toolBar;
    toolBar->setIconSize(QSize(34,34));//默认24

    settingManage = new SettingManage();
    ui->plainTextEdit->setFrameShape(QFrame::Shape::NoFrame);
    textAreaType = 1;
    switch (textAreaType) {
    case 0:
        ui->plainTextEdit->setVisible(true);
        ui->frame->setVisible(false);
        break;
    case 1:
        ui->plainTextEdit->setVisible(false);
        ui->frame->setVisible(true);
        break;
    default:
        ui->plainTextEdit->setVisible(false);
        ui->frame->setVisible(true);
    }
    //
    QFont listFont = settingManage->getListFont();
    list1->setFont(listFont);
    list2->setFont(listFont);
    QFont font = settingManage->getTextFont();
    this->updateTextFont(font);

    settings = settingManage->getSettings();
    rootPath = settingManage->getRootPath();

    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenRect = screen->availableVirtualGeometry();
    int window_wide = settings->value("Notes/window_wide", screenRect.width() * 0.6).toInt();
    int window_high = settings->value("Notes/window_high", screenRect.height() * 0.6).toInt();
    int window_x = settings->value("Notes/window_x", -1).toInt();
    int window_y = settings->value("Notes/window_y", -1).toInt();
    resize(window_wide, window_high);
    if (window_x != -1 || window_y != -1) {
        move(window_x, window_y);
    }
    isDarkTheme = settings->value("Notes/isDarkTheme", false).toBool();
    setthemeColor();
    cleanTextArea();
    LayoutUtils::setLayoutSize(ui->splitter, ui->splitter_2);

    selectData.setRootPath(rootPath);

    ui->plainTextEdit->setFrameShape(QFrame::Shape::NoFrame);
    setSelectColor();
    //----------------------------
    QString aList1Value = settings->value("Notes/list1Value", "").toString();
    QString aList2Value = settings->value("Notes/list2Value", "").toString();

    QStringList aList1 = FileUtils::getDirList(rootPath);
    WidgetUtils::putListItem(list1, aList1);

    QString aList1Path = QDir(rootPath).filePath(aList1Value);
    QStringList aList2 = FileUtils::getFileList(aList1Path);
    WidgetUtils::putListItem(list2, aList2);

    int list1_row = MyUtils::getStringListIndexByValue(aList1,aList1Value);
    int list2_row = MyUtils::getStringListIndexByValue(aList2,aList2Value);

    if (list1_row != -1) list1->setCurrentRow(list1_row);
    if (list2_row != -1) list2->setCurrentRow(list2_row);

    int verticalScroll = settings->value("TextEdit/verticalScroll", 0).toInt();
    if (textAreaType == 0) {//plainTextEdit
        //设置光标位置
        int position = settings->value("TextEdit/position", 0).toInt();
        QTextCursor textCursor = ui->plainTextEdit->textCursor();
        textCursor.setPosition(position);
        ui->plainTextEdit->setTextCursor(textCursor);
        //设置滚动条位置
        if (verticalScroll != 0) ui->plainTextEdit->verticalScrollBar()->setSliderPosition(verticalScroll);
    }
    else if (textAreaType == 1) {//ui->frame
        //设置光标位置
        int line = settings->value("TextEdit/CursorPosition_line", 0).toInt();
        int index = settings->value("TextEdit/CursorPosition_index", 0).toInt();
        ui->frame->setCursorPosition(line, index);
        ui->frame->setCaretLineBackgroundColor(Qt::lightGray);
        ui->frame->SendScintilla(QsciScintilla::SCI_SETFIRSTVISIBLELINE, line);
        //设置滚动条位置
        if (verticalScroll != 0) ui->frame->verticalScrollBar()->setSliderPosition(verticalScroll);
    }
}

void MainWindow::setthemeColor()
{
    if (isDarkTheme) {
        QString darkColor = "background-color:rgb(25,25,25);color:rgb(178,178,178)";
        ui->toolBar->setStyleSheet(darkColor);
        ui->statusbar->setStyleSheet(darkColor);
        //ui->centralwidget->setStyleSheet(darkColor);
        //ui->list1->setStyleSheet(darkColor);
        ui->splitter_2->setStyleSheet(darkColor);

        defaultTextColorName = "yellow";
    }
    else {
        defaultTextColorName = "#000000";
    }
}

void MainWindow::updateTextFont(QFont font)
{
    ui->frame->setAllFonts(font);
    ui->plainTextEdit->setFont(font);
}

void MainWindow::showExplorer(QString path)
{
    path = QDir::toNativeSeparators(path);

    QProcess proce;
    QString cmd = QString("explorer /select, \"%1\"").arg(path);
    proce.startDetached(cmd);
}

void MainWindow::setSelectColor()
{
    QPalette palette = ui->plainTextEdit->palette();
    if (isDarkTheme) {
        palette.setColor(QPalette::Highlight, QColor("#1D545C"));
        palette.setColor(QPalette::HighlightedText, QColor(Qt::darkGray));
    }
    else {
        palette.setColor(QPalette::Highlight, QColor(Qt::black));
        palette.setColor(QPalette::HighlightedText, QColor(Qt::white));
    }
    ui->plainTextEdit->setPalette(palette);
}

void MainWindow::on_list1_itemSelectionChanged()
{
    //目录列表
    showFileList();
    qDebug() << "打开目录11-" << list1->currentItem()->text();
}
void MainWindow::on_list2_itemSelectionChanged()
{
    if (isClearList2) {
        return;
    }
    qDebug() << "打开文件22-" << list2->currentItem()->text();
    showFileText();
}

void MainWindow::on_list1_itemChanged(QListWidgetItem *item)
{
    //修改目录名
    QString value = item->text();
    QString oldValue = selectData.getDirText();
    QString oldName = selectData.getDirPath();
    if (oldValue == value) {
        return;
    }

    QString dirPath = QDir(rootPath).filePath(value);
    QDir dir(dirPath);
    if (dir.exists()) {
        // 目录存在
        QMessageBox::warning(this, "警告", value + " 目录已存在，请修改目录名");
        item->setText(selectData.getDirText()); // 恢复原来的值
        return;
    }
    selectData.setDirText(value);
    QString newName = selectData.getDirPath();
    bool ren = QFile::rename(oldName, newName);
    if (!ren) {
        qDebug() << oldValue << "文件名修改失败!";
        selectData.setDirText(oldValue);
    }
}

void MainWindow::on_list2_itemChanged(QListWidgetItem *item)
{
    //修改文件名
    QString value = item->text();
    QString oldValue = selectData.getFileText();
    if (oldValue == value) {
        return;
    }
    QString filePath = QDir(selectData.getDirPath()).filePath(value);
    QFile file(filePath);
    if (file.exists()) {
        // 文件存在
        QMessageBox::warning(this, "警告", value + " 文件已存在，请修改文件名");
        item->setText(selectData.getFileText()); // 恢复原来的值
        return;
    }
    QString oldName = selectData.getCurFile();
    selectData.setFileText(value);
    QString newName = selectData.getCurFile();
    bool ren = QFile::rename(oldName, newName);
    if (!ren) {
        qDebug() << oldValue << "文件名修改失败!";
        selectData.setFileText(oldValue);
    }else{
        QFileInfo fileInfo(newName);
        QString fileName = fileInfo.fileName();
        QString suffix = fileInfo.suffix();
        qDebug() << newName << "文件名修改成功!\nfileName="<<fileName<<","<<"suffix="<<suffix;
        ui->frame->updateLexer(fileName, suffix);
    }
}

void MainWindow::on_list1_customContextMenuRequested(const QPoint &pos)
{
    qDebug() << "目录右键_" << list1->currentItem()->text();
    //目录右键
    showFileList();
    if (list1->itemAt(pos) != NULL) {
        popMenu_L->exec(QCursor::pos());
    }
}

void MainWindow::on_list2_customContextMenuRequested(const QPoint &pos)
{
    //文件右键
    showFileText();
    if (list2->itemAt(pos) != NULL) {
        popMenu_R->exec(QCursor::pos());
    }
}

void MainWindow::on_makeDir_clicked()
{
    makeDir();
}

void MainWindow::on_makeFile_clicked()
{
    makeFile();
}

void MainWindow::on_plainTextEdit_textChanged()
{
    if (list2->currentRow() != -1 && isSaveFile && currentFile.isEmpty()) {
        MyUtils::setItemTextColor(list2->currentItem(), "red");
        isSaveFile = false;
    }
    ui->frame->updateLineNumberWidth();//设置页边宽度
}

void MainWindow::on_list2_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    //切换选择item时候调用
    if (current != nullptr) {
    }
    if (previous != nullptr && (QColor().black() != previous->foreground().color().value())) {
        MyUtils::setItemTextColor(previous, defaultTextColorName);
    }
}

void MainWindow::newDocument()
{
    qDebug() << "newDocument";
}

void MainWindow::open()
{
    //QString fileName = QFileDialog::getOpenFileName(this, "Open the file");
    QString fileName = QFileDialog::getOpenFileName(this, "Open the file", QDir::homePath());
    QFile file(fileName);
    currentFile = fileName;
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        //QMessageBox::warning(this, "Warning", "Cannot open file: " + file.errorString());
        return;
    }
    file.close();

    setWindowTitle(fileName);
    QString text = FileUtils::getFileString(fileName);
    setTextArea(text);

    if (list2->currentRow() != -1) {
        isClearList2 = true;
        list2->currentItem()->setSelected(false);
        //        list2->setCurrentItem(nullptr);
        isClearList2 = false;
    }
}

void MainWindow::save()
{
    if (!ui->frame->isEnabled()) {
        return;
    }
    QString text = getTextArea();
    if (currentFile.isEmpty()) {
        if (list2->currentRow() != -1) {
            if (isSaveFile) {
                return;
            }
            MyUtils::setItemTextColor(list2->currentItem(), defaultTextColorName);
            QString filename = selectData.getCurFile();
            //qDebug() << "filename=" << filename;
            FileUtils::writeStringToFile(filename, text);
            setWindowTitle(selectData.getDirText() + "/" + selectData.getFileText());
            isSaveFile = true;
        }
        else {
            saveAs(selectData.getRootPath());
        }
    }
    else {
        FileUtils::writeStringToFile(currentFile, text);
    }
}

void MainWindow::saveAsAct()
{
    if (!ui->frame->isEnabled()) {
        return;
    }
    if (currentFile.isEmpty()) {
        saveAs(QDir::homePath() + "/" + selectData.getFileText());
    }
    else {
        saveAs(currentFile);
    }
}
void MainWindow::saveAs(QString defaultName)
{
    QString fileName = QFileDialog::getSaveFileName(this, "Save as", defaultName);
    //QString fileName = QFileDialog::getSaveFileName(this, "Save as");
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        //QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
        return;
    }
    currentFile = fileName;
    setWindowTitle(fileName);
    QString text = getTextArea();
    FileUtils::writeStringToFile(fileName, text);
}

void MainWindow::copy()
{
#if QT_CONFIG(clipboard)
    if(textAreaType==0)
    {
        ui->plainTextEdit->copy();
    }
    else if(textAreaType==1)
    {
        ui->frame->copy();
    }
#endif
}
void MainWindow::cut()
{
#if QT_CONFIG(clipboard)
    if(textAreaType==0)
    {
        ui->plainTextEdit->cut();
    }
    else if(textAreaType==1)
    {
        ui->frame->cut();
    }
#endif
}
void MainWindow::paste()
{
#if QT_CONFIG(clipboard)
    if(textAreaType==0)
    {
        ui->plainTextEdit->paste();
    }
    else if(textAreaType==1)
    {
        ui->frame->paste();
    }
#endif
}
void MainWindow::undo()
{
    if(textAreaType==0)
    {
        ui->plainTextEdit->undo();
    }
    else if(textAreaType==1)
    {
        ui->frame->undo();
    }
}
void MainWindow::redo()
{
    if(textAreaType==0)
    {
        ui->plainTextEdit->redo();
    }
    else if(textAreaType==1)
    {
        ui->frame->redo();
    }
}

void MainWindow::selectFont()
{
    bool fontSelected;
    //    QFont font = QFontDialog::getFont(&fontSelected, this);
    QFont font = QFontDialog::getFont(&fontSelected, ui->frame->getCurrentFont(), this);
    if (fontSelected) {
        //        ui->plainTextEdit->setFont(font);
        ui->frame->setFont(font);
        ui->frame->setAllFonts(font);

        settings->setValue("TextEdit/fontFamily",font.family());
        settings->setValue("TextEdit/fontSize",font.pointSize());
        settings->setValue("TextEdit/fontBold",font.bold());
    }
}

void MainWindow::about()
{
    QMessageBox::about(this, "关于 NotesQT备忘录程序",
                       "NotesQT备忘录程序 v1.0\n"
                       "开发者：杨洋\n"
                       "版权所有 ©2023. All rights reserved.\n"
                       "\n"
                       "项目描述：\n"
                       "NotesQT备忘录程序是一款简单易用的电子备忘录应用，帮助用户快速记录和管理重要的信息和想法。\n"
                       "\n"
                       "功能列表：\n"
                       "- 创建、编辑和删除笔记\n"
                       "- 保存和加载笔记\n"
                       "- 自动保存功能\n"
                       "- 笔记搜索和过滤功能\n"
                       "- 支持多个笔记本\n"
                       "- 云同步功能（未来版本）\n"
                       "\n"
                       "快捷键列表：\n"
                       "- 新建笔记：Ctrl+N\n"
                       "- 保存笔记：Ctrl+S\n"
                       "- 搜索笔记：Ctrl+F\n"
                       "- 删除笔记：Delete\n"
                       "\n"
                       "感谢列表：\n"
                       "- QT开发团队\n"
                       "- Stack Overflow社区\n"
                       "\n"
                       "联系方式：\n"
                       "- 邮箱：w823901622@163.com\n"
                       "- 网站：(您的网站地址)\n"
                       "\n"
                       "免责声明：\n"
                       "NotesQT备忘录程序可能会出现一些错误或漏洞。作者不对因使用此程序而造成的任何损失负责。\n"
                       "\n"
                       "开源信息：\n"
                       "NotesQT备忘录程序是一款开源软件。源代码可在 (您的代码库地址) 中获取。");
}

void MainWindow::exit()
{
    this->close();
    //    QCoreApplication::quit();
}

void MainWindow::on_actionJumpToTopButton_triggered()
{
    if (textAreaType == 0) {
        ui->plainTextEdit->verticalScrollBar()->setValue(ui->plainTextEdit->verticalScrollBar()->minimum());
    }
    else if (textAreaType == 1) {
        ui->frame->SendScintilla(ui->frame->SCI_GOTOPOS, 0);
    }
}

void MainWindow::on_actionJumpToBottomButton_triggered()
{
    if (textAreaType == 0) {
        ui->plainTextEdit->verticalScrollBar()->setValue(ui->plainTextEdit->verticalScrollBar()->maximum());
    }
    else if (textAreaType == 1) {
        ui->frame->SendScintilla(ui->frame->SCI_GOTOPOS, ui->frame->length());
    }
}

void MainWindow::applySetting()
{
    qDebug() << "应用设置applySetting";
}

void MainWindow::showDir()
{
    showExplorer(selectData.getDirPath());
}
void MainWindow::showFile()
{
    showExplorer(selectData.getCurFile());
}

void MainWindow::deleteDir()
{
    QString path = selectData.getDirPath();
    int ret = QMessageBox::question(this,"删除","确定删除：" + selectData.getDirText() + " ?",
                                    QMessageBox::Yes | QMessageBox::Cancel);
    if (ret != QMessageBox::Yes) {
        return;
    }
    QDir dir(path);
    bool s = dir.removeRecursively();
    if (s) {
        //qDebug() << path << ",删除成功√";
        QListWidgetItem *item = list1->currentItem();
        list1->removeItemWidget(item);
        delete item;
        selectData.setRowDir(-1);
        showFileList();
    }
    else {
        qDebug() << path << ",删除失败!";
    }
}

void MainWindow::deleteFile()
{
    QString filename = selectData.getCurFile();
    int ret = QMessageBox::question(this,"删除","确定删除：" + selectData.getFileText() + " ?",
                                    QMessageBox::Yes | QMessageBox::Cancel);
    if (ret != QMessageBox::Yes) {
        return;
    }
    bool s = QFile::remove(filename);
    if (s) {
        //qDebug() << filename << ",删除成功√";
        QListWidgetItem *item = list2->currentItem();
        list2->removeItemWidget(item);
        delete item;
        selectData.setRowFile(-1);
        showFileText();
    }
    else {
        qDebug() << filename << ",删除失败!";
    }
}

//########################################################

QListWidgetItem *MainWindow::makeDir()
{
    QString dir_str = MyUtils::getNewDirName(selectData.getRootPath());
    QString fileName = selectData.getRootPath() + "/" + dir_str;
    // 检查目录是否存在，若不存在则新建
    QDir dir;
    if (!dir.exists(fileName)) {
        bool res = dir.mkpath(fileName);
        if (res == false) {
            qDebug() << "目录创建失败X!" << fileName;
        }
    }
    QListWidgetItem *aitem = new QListWidgetItem(dir_str);
    aitem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
    list1->addItem(aitem);
    return aitem;
}

QListWidgetItem *MainWindow::makeFile()
{
    QDir dir;
    if (!dir.exists(selectData.getDirPath())) {
        //如果存在上级目录就创建文件
        qDebug() << selectData.getDirPath() << ",目录不存在!";
        return nullptr;
    }
    QString newName = MyUtils::getNewFileName(selectData.getDirPath());
    QString fileName = selectData.getDirPath() + "/" + newName;
    QFile file(fileName);
    if (!file.exists(fileName)) {
        bool x = file.open(QIODevice::WriteOnly | QIODevice::Text);
        if (x == false) {
            qDebug() << "文件出创建失败X!" << file.fileName();
        }
        file.close();
    }
    QListWidgetItem *aitem = new QListWidgetItem(newName);
    aitem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);
    list2->addItem(aitem);
    return aitem;
}


void MainWindow::showFileList()
{
    bool isSelected = list1->currentItem()->isSelected();
    QListWidgetItem *selItem = list1->selectedItems().takeAt(0);
    QListWidgetItem *curItem = list1->currentItem();
    bool noSelect = selItem == curItem;
    if (!isSelected || !noSelect) {//判断是不是当前选择的Item
        qDebug() << "list1判断是不是当前选择的Item!" << " selItem=" << selItem->text() << " curItem=" << curItem->text();
        list1->setCurrentItem(selItem);
        selItem->setSelected(true);
    }

    int rowDir = list1->currentRow();
    if (rowDir != -1) {
        QString value = list1->currentItem()->text();
        selectData.setDirText(value);
        selectData.setRowDir(rowDir);
        if (selectData.isSelectDir()) {
            return;
        }
    }

    isClearList2 = true;
    list2->clear();
    isClearList2 = false;

    cleanTextArea();

    QString dirPath = selectData.getDirPath();
    setWindowTitle(list1->currentItem()->text());
    QStringList list = FileUtils::getFileList(dirPath);
    WidgetUtils::putListItem(list2, list);

}

void MainWindow::showFileText()
{
    int rowFile = list2->currentRow();

    if (rowFile != -1) {//解决点解 list2 空白处 向上拖动鼠标选择最后一行报错问题 curItem->isSelected() 异常报错
        QListWidgetItem *selItem = list2->selectedItems().takeAt(0);
        QListWidgetItem *curItem = list2->currentItem();
        bool isSelected = curItem->isSelected();
        bool noSelect = selItem == curItem;
        if (!isSelected || !noSelect) {//判断是不是当前选择的Item
            qDebug() << "list2判断是不是当前选择的Item!" << " selItem=" << selItem->text() << " curItem=" << curItem->text();
            list2->setCurrentItem(selItem);
            selItem->setSelected(true);
        }
    }

    if (!currentFile.isEmpty()) {
        currentFile.clear();
    }

    if (rowFile == -1) {
        cleanTextArea();
        return;
    }
    else {
        QString value = list2->currentItem()->text();
        selectData.setFileText(value);
        selectData.setRowFile(rowFile);
        if (selectData.isSelectFile()) {
            return;
        }
        QString absName = selectData.getCurFile();
        setWindowTitle(list1->currentItem()->text() + "/" + value);
        QFileInfo fileInfo(absName);
        if (fileInfo.isFile()) {
            QString fileName = fileInfo.fileName();
            QString suffix = fileInfo.suffix();
            ui->frame->updateLexer(fileName, suffix);
            QString text = FileUtils::getFileString(absName);
            setTextArea(text);
        }
        else {
            cleanTextArea();
        }
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    settings->setValue("Notes/isDarkTheme", isDarkTheme);

    bool isNoState = windowState() == Qt::WindowNoState;
    if (isNoState) {
        int window_x = this->frameGeometry().x();
        int window_y = this->frameGeometry().y();
        int window_wide = this->geometry().width();
        int window_high = this->geometry().height();

        settings->setValue("Notes/window_x", window_x);
        settings->setValue("Notes/window_y", window_y);
        settings->setValue("Notes/window_wide", window_wide);
        settings->setValue("Notes/window_high", window_high);
    }

    int list1_row = list1->currentRow();
    int list2_row = list2->currentRow();
    QString list1Value = list1_row == -1 ? "" : list1->currentItem()->text();
    QString list2Value = list2_row == -1 ? "" : list2->currentItem()->text();

    settings->setValue("Notes/list1Value", list1Value);
    settings->setValue("Notes/list2Value", list2Value);

    if (textAreaType == 0) {
        //#include <QScrollBar> 需要包含头文件才能用 sliderPosition
        settings->setValue("TextEdit/verticalScroll", ui->plainTextEdit->verticalScrollBar()->sliderPosition());
        //得到光标位置
        settings->setValue("TextEdit/position", ui->plainTextEdit->textCursor().position());
    }
    else if (textAreaType == 1) {
        settings->setValue("TextEdit/verticalScroll", ui->frame->verticalScrollBar()->sliderPosition());
        //得到光标位置
        int line, index;
        ui->frame->getCursorPosition(&line, &index);
        settings->setValue("TextEdit/CursorPosition_line", line);
        settings->setValue("TextEdit/CursorPosition_index", index);
    }
}

//
// 清空TextArea
//
void MainWindow::cleanTextArea()
{
    isSaveFile = false;
    isClearTextArea = true;

    if(textAreaType==0)
    {
        ui->plainTextEdit->setEnabled(false);
        ui->plainTextEdit->clear();
    }else if(textAreaType==1){
        ui->frame->setEnabled(false);
        ui->frame->clear();
    }

    isSaveFile = true;
    isClearTextArea = false;
}

//
// 添加TextArea文本
//
void MainWindow::setTextArea(QString text)
{
    isSaveFile = false;
    isClearTextArea = true;

    if(textAreaType==0)
    {
        ui->plainTextEdit->clear();
        ui->plainTextEdit->setEnabled(true);
        ui->plainTextEdit->setPlainText(text);
    }else if(textAreaType==1){
        ui->frame->clear();
        ui->frame->setEnabled(true);
        ui->frame->setText(text);
        ui->frame->setScrollWidth(5);
    }
    isSaveFile = true;
    isClearTextArea = false;
}

//
// 获取TextArea文本
//
QString MainWindow::getTextArea()
{
    QString text;
    if(textAreaType==0)
    {
        text = ui->plainTextEdit->toPlainText();
    }
    else if(textAreaType==1)
    {
        text = ui->frame->text();
    }
    return text;
}
